package com.roobo.demo;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.roobo.mqttsdk.manager.CustomManager;
import com.roobo.mqttsdk.manager.ResultInterface;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;

/**
 * 设备 公众号微聊
 */


public class VoiceChatActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String TAG = VoiceChatActivity.class.getSimpleName();
    public static final String MESSAGE = "message";
    public static final String CMD_TAG = "cmd";
    public static final String CMD_PLAY_VOICE = "playVoice";
    public static final String CMD_SHOW_TEXT_NO_TTS = "showTextNoTTS";

    public static final String URL_TAG = "url";
    public static final String VOICE_FILE_NAME = "demo.amr";

    private TextView mMessageTv;
    private Button mStartRecordBtn;
    private Button mStopRecordBtn;

    private MyRecordCenter mRecordCenter;
    private String mVoicePath;

    private boolean mIsStartRecordSuccess;
    private boolean mIsStopRecordSuccess;


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        playVoice(intent);
    }

    /**
     * 播放语音
     *
     * @param intent
     */
    private void playVoice(Intent intent) {
        String message = intent.getStringExtra(MESSAGE);
        Log.d(TAG, "playVoice message:" + message);
        mMessageTv.setText(message);
        if (!TextUtils.isEmpty(message)) {
            try {
                JSONObject object = new JSONObject(message);
                String cmd = object.getString(CMD_TAG);
                if (CMD_PLAY_VOICE.equals(cmd)) {//播放音频
                    MyMediaPlayer.getInstance().prepare(object.getString(URL_TAG));
                    Toast.makeText(this, getResources().getString(R.string.play_voice), Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Log.d(TAG, "playVoice ee.getLocalizedMessage:" + e.getLocalizedMessage());
            }
        } else {
            Log.d(TAG, "playVoice message为空");
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice_chat);
        setTitle(getResources().getString(R.string.voice_chat_activity_title));
        initViews();
        MainActivity.applyPermission(this);
        playVoice(getIntent());
        mRecordCenter = new MyRecordCenter(this);
    }

    private void initViews() {
        mMessageTv = findViewById(R.id.message_tv);
        mStartRecordBtn = findViewById(R.id.start_record_btn);
        mStopRecordBtn = findViewById(R.id.stop_record_btn);

        mStartRecordBtn.setOnClickListener(this);
        mStopRecordBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_record_btn:
                mVoicePath = createVoiceFile(VOICE_FILE_NAME);
                if (TextUtils.isEmpty(mVoicePath)) {
                    Toast.makeText(VoiceChatActivity.this, getResources().getString(R.string.create_voice_file_fail), Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(this, getResources().getString(R.string.speak_to_the_mic), Toast.LENGTH_SHORT).show();
                mIsStartRecordSuccess = mRecordCenter.startRecord(mVoicePath);
                if (!mIsStartRecordSuccess) {
                    Toast.makeText(VoiceChatActivity.this, getResources().getString(R.string.record_voice_fail), Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.stop_record_btn:
                if (!mIsStartRecordSuccess) {
                    Toast.makeText(VoiceChatActivity.this, getResources().getString(R.string.plz_click_start_record), Toast.LENGTH_SHORT).show();
                    return;
                }
                mIsStopRecordSuccess = mRecordCenter.stopRecord();
                if (!mIsStopRecordSuccess) {
                    Toast.makeText(VoiceChatActivity.this, getResources().getString(R.string.record_voice_fail), Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(this, getResources().getString(R.string.send_voice), Toast.LENGTH_SHORT).show();
                Log.d(TAG, "voiceDuration:" + mRecordCenter.getVoiceDuration());
                CustomManager.getInstance().sendVoiceFile(mVoicePath, mRecordCenter.getVoiceDuration(), new ResultInterface() {
                    @Override
                    public void onResult(int code, String message) {//非主线程
                        Log.d(TAG, "sendVoiceFile onResult code：" + code + " message:" + message);
                        if (code == CustomManager.SEND_SUCCESS) {
                            Toast.makeText(VoiceChatActivity.this, getResources().getString(R.string.send_voice_success), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(VoiceChatActivity.this, getResources().getString(R.string.send_voice_fail), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                mIsStartRecordSuccess = false;
                mIsStopRecordSuccess = false;
                break;
        }
    }

    /**
     * 判断SDCard是否存在
     *
     * @return
     */
    public static boolean isSdCardExist() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 創建语音文件
     *
     * @return
     */
    public String createVoiceFile(String voidFileName) {
        boolean exist = isSdCardExist();
        if (!exist) {
            Log.v(TAG, "createVoiceFile isSdCardExist=false");
            return "";
        }
        String path = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + File.separator + voidFileName;//语音文件
        File mFile = new File(path);
        if (mFile.exists()) {
            Log.d(TAG, getResources().getString(R.string.voice_file_exists));
        } else {
            Log.d(TAG, getResources().getString(R.string.voice_file_no_exists));
            try {
                mFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                Log.v(TAG, "createVoiceFile e.getLocalizedMessage.:" + e.getLocalizedMessage());
                path = "";
            }
        }
        return path;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyMediaPlayer.getInstance().release();
        if (mRecordCenter != null) {
            mRecordCenter.stopRecord();
        }
    }
}
